
package com.universest.swordholder.model.user

import android.content.Context
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.preferencesDataStoreFile
import com.universest.swordholder.data.AppDatabase
import com.universest.swordholder.data.dao.User
import com.universest.swordholder.data.repository.UserRepository
import com.universest.swordholder.getApplicationContext
import com.universest.swordholder.model.config.ConfigManager
import com.universest.swordholder.tools.toMD5
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

class UserManager private constructor(
    private val appDatabase: AppDatabase,
    private val context: Context
) {
    // 常量定义，提高可维护性
    companion object {
        private const val DATA_STORE_PREFIX = "sh_user_"
        private val DEFAULT_USER = User(0, "guest", "游客", "")
        val instance: UserManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            UserManager(
                appDatabase = AppDatabase.getInstance(getApplicationContext()),
                context = getApplicationContext()
            )
        }
    }

    // 当前用户，使用volatile保证多线程可见性
    @Volatile
    private var _currentUser: User = DEFAULT_USER

    // 添加MutableStateFlow用于发射用户变化
    private val _currentUserFlow = MutableStateFlow(DEFAULT_USER)
    val currentUserFlow: StateFlow<User> = _currentUserFlow

    // 暴露不可变的当前用户
    val currentUser: User
        get() = _currentUser

    val currentUserId: Int
        get() = _currentUser.userId

    // 用户配置相关
    @Volatile
    private var userConfigManager: ConfigManager? = null
    @Volatile
    private var lastConfigUserId: Int = -1  // 记录上次配置对应的用户ID，初始值无效

    private val userRepository
        get() = UserRepository(appDatabase)

    /**
     * 用户登录验证
     * @return 登录成功返回用户信息，失败返回null
     */
    suspend fun login(userName: String, password: String): User? {
        // 从数据库查询用户
        val user = userRepository.getUserByUserName(userName).first()

        // 验证用户密码并更新当前用户
        return if (user != null && validatePassword(password, user.password)) {
            _currentUser = user
            _currentUserFlow.value = user // 更新Flow的值
            user
        } else {
            null
        }
    }

    /**
     * 获取当前用户的配置管理器（单例）
     */
    fun getUserConfigManager(): ConfigManager {
        // 双重检查锁定，避免不必要的同步
        if (userConfigManager?.let { lastConfigUserId == currentUserId } == true) {
            return userConfigManager!!
        }

        return synchronized(this) {
            if (lastConfigUserId != currentUserId) {
                // 用户ID变化时重新创建配置管理器
                lastConfigUserId = currentUserId
                val dataStore = PreferenceDataStoreFactory.create(
                    produceFile = { context.preferencesDataStoreFile("${DATA_STORE_PREFIX}$currentUserId") }
                )
                userConfigManager = ConfigManager(dataStore)
            }
            userConfigManager!!
        }
    }
    /**
     * 密码验证逻辑封装
     */
    private fun validatePassword(inputPassword: String, storedPassword: String): Boolean {
        // 特殊情况：数据库密码为空时，仅允许空密码登录
        if (storedPassword.isEmpty()) {
            return inputPassword.isEmpty()
        }
        // 常规情况：MD5加密比对
        return inputPassword.toMD5() == storedPassword
    }

}